package com.risetechnology.adapter;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.risetechnology.common.Const;
import com.risetechnology.common.Shared;
import com.risetechnology.data.Shopping;
import com.risetechnology.krystalkitchen1.ActivityShoppingDetails;
import com.risetechnology.krystalkitchen1.ActivityShoppingList;
import com.risetechnology.krystalkitchen1.ChooseEmailDialog;
import com.risetechnology.krystalkitchen1.R;
import com.risetechnology.krystalkitchen1.TabsManager;
import com.risetechnology.master.NavigationActivity;
import com.risetechnology.utils.threads.SendEmailShopingItem;

public class ShoppingListAdapter extends ArrayAdapter<Shopping> {

	private Activity context, parent;
	private int layoutId;
	private List<Shopping> data = null;
	private Shopping curShopping = null;

	public ShoppingListAdapter(Activity context, int layoutId,
			List<Shopping> data) {
		super(context, layoutId, data);
		this.context = context;
		parent = context.getParent();
		this.layoutId = layoutId;
		this.data = data;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(layoutId, parent, false);

			holder = new ViewHolder();

			holder.textViewName = (TextView) convertView
					.findViewById(R.id.tv_shopping_name);
			// holder.layoutDetails = (LinearLayout)
			// convertView.findViewById(R.id.layout_details);
			holder.layoutSend = (LinearLayout) convertView
					.findViewById(R.id.ll_send);
			holder.layoutDelete = (LinearLayout) convertView
					.findViewById(R.id.ll_delete);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		holder.textViewName.setText(data.get(position).getName());

		holder.layoutSend.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				curShopping = data.get(position);
				if(null != curShopping){
					showOptionsDialog();
				}
			}
		});

		holder.layoutDelete.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showDeleteShoppingDialog(data.get(position).getName(), data
						.get(position).getId());
			}
		});

		convertView.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(View v) {
				showEditShoppingListName(data.get(position).getId(),
						data.get(position).getName());
				return false;
			}
		});

		convertView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(((NavigationActivity) context)
						.getParent(), ActivityShoppingDetails.class);
				intent.putExtra(Const.KEY_SHOPPING_NAME, data.get(position)
						.getName());
				intent.putExtra(Const.KEY_ID, data.get(position).getId());
				((NavigationActivity) context).goNextHistory(
						"Shopping Details", intent);
			}
		});

		return convertView;
	}

	@SuppressWarnings("deprecation")
	private void showOptionsDialog() {
		if (!TabsManager.loadMailOk) {
			Toast.makeText(getContext(), "Getting mail contact...\nTry again in a few secs.",
					Toast.LENGTH_SHORT).show();
			return;
		}
		
		final Dialog dialog = new Dialog(parent);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_send_email_options);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		LinearLayout cameraLayout = (LinearLayout) dialog
				.findViewById(R.id.layout_camera);
		cameraLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				showInputEmailDialog(0);
			}
		});

		LinearLayout galleryLayout = (LinearLayout) dialog
				.findViewById(R.id.layout_gallery);
		galleryLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				showInputEmailDialog(1);
			}
		});

		dialog.show();
	}
	
	private void showInputEmailDialog(int type) {
		if(type != 0){// Input mail
			new ChooseEmailDialog(parent,
					TabsManager.mails, 
					new ChooseEmailDialog.SelectedListener() {

						@Override
						public void onSelected(ArrayList<String> choosenRecipe) {
							String email = "";
							if(choosenRecipe.size()>0){
								email = choosenRecipe.get(0);
							}
							for (int i = 1; i < choosenRecipe.size(); i++) {
								email += "," + choosenRecipe.get(i);
							}
							
							new SendEmailShopingItem(context, curShopping, email).execute();
						}
					}).show();
			
		}else{
			final Dialog dialog = new Dialog(parent);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.dialog_input_part_name);
	
			Window window = dialog.getWindow();
			WindowManager.LayoutParams wlp = window.getAttributes();
	
			wlp.gravity = Gravity.CENTER;
			wlp.width = WindowManager.LayoutParams.FILL_PARENT;
			wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
			window.setAttributes(wlp);
	
			dialog.getWindow().setAttributes(wlp);
	
			dialog.show();
	
			TextView tv = (TextView) dialog.findViewById(R.id.tv_title);
			tv.setText("Input Email Address");
	
			final EditText edt_email = (EditText) dialog
					.findViewById(R.id.et_part_name);
			edt_email.setHint("Input Email Address");
			edt_email.setInputType(InputType.TYPE_CLASS_TEXT
					| InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
	
			// edt_email.setText("ninhngoc.t4.bkdn@gmail.com");
	
			Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
			buttonOK.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					String email = edt_email.getText().toString();
					if (email.trim().length() == 0) {
						Toast.makeText(context,
								"Please input email", Toast.LENGTH_SHORT).show();
						return;
					}
					if (!isEmailValid(email)) {
						Toast.makeText(context,
								"Please input correct email!", Toast.LENGTH_SHORT)
								.show();
						return;
					}
	
					
	
					new SendEmailShopingItem(context, curShopping, email).execute();
	
					dialog.dismiss();
				}
			});
		
		}
	}
	
	boolean isEmailValid(CharSequence email) {
		return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
	}
	
	static class ViewHolder {
		TextView textViewName;
		LinearLayout layoutDetails;
		LinearLayout layoutSend;
		LinearLayout layoutDelete;
	}

	@SuppressWarnings("deprecation")
	private void showDeleteShoppingDialog(String shoppingName,
			final String shoppingListId) {
		AlertDialog dialog = new AlertDialog.Builder(
				((NavigationActivity) context).getParent()).create();
		dialog.setMessage("Delete " + shoppingName);

		dialog.setButton("YES", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				Shared.dbAdapter.deleteShoppingList(shoppingListId);
				ActivityShoppingList.getShoppingList();
			}
		});

		dialog.setButton2("NO", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		dialog.show();
	}

	@SuppressWarnings("deprecation")
	private void showEditShoppingListName(final String id, String name) {
		final Dialog dialog = new Dialog(
				((NavigationActivity) context).getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_edit_shopping_list);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText edittextName = (EditText) dialog
				.findViewById(R.id.et_shopping_list_name);
		edittextName.setText(name);

		Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
		buttonOK.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String newName = edittextName.getText().toString();
				if (newName == null || newName.length() == 0) {
					Toast.makeText(((NavigationActivity) context).getParent(),
							"Please input shopping list name!",
							Toast.LENGTH_SHORT).show();
					return;
				}
				dialog.dismiss();

				Shopping shopping = new Shopping(id, newName);
				Shared.dbAdapter.updateShoppingList(shopping);

				ActivityShoppingList.getShoppingList();
			}
		});
	}
}